package com.example.cloudprinter.network.converter;

import com.alibaba.fastjson.JSON;
import com.example.cloudprinter.network.RequestBean;
import com.example.cloudprinter.network.RequestError;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private final Type type;

    FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String string = value.string();
        RequestBean bean = JSON.parseObject(string, RequestBean.class);
        //请求成功后，过滤掉其他值，直接返回datas实体
        if (bean.getErrno() == 0) {
            if (type == String.class)
                return (T) bean.getData();
            return JSON.parseObject(bean.getData(), type);
        }
        //各种请求异常时，返回封装好的表示错误的实体数据
        throw new RequestError(bean);
    }
}
